import sys
import urllib

from PyQt5.QtWidgets import QApplication, QLabel, QDoubleSpinBox, QComboBox, QGridLayout, QDialog


class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.rates = {}
        date = self.getdata() #只在init过程中用到的变量，可以不带self
        rates = sorted(self.rates.keys())

        dateLabel = QLabel(date)
        self.fromComboBox = QComboBox()
        self.fromComboBox.addItems(rates)
        self.fromComboBox.setToolTip("来源货币")#add tip
        self.fromSpinBox = QDoubleSpinBox()

        self.fromSpinBox.setRange(0.01, 100000000.00)
        self.fromSpinBox.setValue(1.00)
        self.fromSpinBox.setToolTip("兑换金额")#add tip
        self.toComboBox = QComboBox()
        self.toComboBox.addItems(rates)
        self.toComboBox.setToolTip("目标货币")
        self.toLabel = QLabel("1.00")

        grid = QGridLayout()
        grid.addWidget(dateLabel, 0, 0)
        grid.addWidget(self.fromComboBox, 1, 0)
        grid.addWidget(self.fromSpinBox, 1, 1)
        grid.addWidget(self.toComboBox, 2, 0)
        grid.addWidget(self.toLabel, 2, 1)
        self.setLayout(grid)

        self.fromComboBox.currentIndexChanged.connect(self.updateUI)
        self.toComboBox.currentIndexChanged.connect(self.updateUI)
        self.fromSpinBox.valueChanged.connect(self.updateUI)

        self.setWindowTitle("Currency")

    def updateUI(self):
        to = self.toComboBox.currentText()
        from_ = self.fromComboBox.currentText()
        amount = (self.rates[from_] / self.rates[to]) * self.fromSpinBox.value()
        self.toLabel.setText("%0.2f" % amount)

    def getdata(self):
        """这个摊上大事了，因为事过多年，加拿大银行的网址变了，数据格式也变了，只好按新的数据，略加整理，
        可以在不改变程序大方向的前提下，得以进行。
        urllib就不练了吧，好像不行。改本地文件"""
        try:
            date = "Unknown"
            with open('exchange.csv') as fh:
                for line in fh:
                    fields = line.split(",")
                    if line.startswith('Date'):
                        date = fields[-1]
                        print(date)
                    else:
                        try:
                            value = float(fields[-1])
                            self.rates[fields[0]] = value
                        except ValueError:
                            pass
                return "Exchange Rates Date: " + date
        except Exception as e:
            return "Failed to Download: %s" % e


if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = Form()
    form.show()
    sys.exit(app.exec())
